package com.itheima.bigevents.controller;

import com.itheima.bigevents.pojo.Result;
import com.itheima.bigevents.pojo.User;
import com.itheima.bigevents.service.UserService;
import com.itheima.bigevents.utils.Md5Util;
import com.itheima.bigevents.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.itheima.bigevents.utils.JwtUtil;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Validated //@Validated注解+@Pattern注解=开启参数校验
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名必须是5-16位的字母、数字、下划线、减号") String username, @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,16}$", message = "密码必须是6-16位的字母和数字") String password) {
        //判断是否已经注册
        //查找用户名是否存在
        User user =userService.findByUsername(username);
        if(user==null){
            //进行注册
            userService.register(username, password);
            return Result.success();
//            return Result.success("注册成功").toString(); 如果register()的返回类型是String，则toString()方法
        }else{
            return Result.error("用户名已存在");
        }


    }

    @RequestMapping(value ="/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public Result login(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$", message = "用户名必须是5-16位的字母、数字、下划线、减号") String username, @Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,16}$", message = "密码必须是6-16位的字母和数字") String password) {
        log.info("username:{},password:{}",username,password);
        User user = userService.findByUsername(username);
            if(userService.login(username, password)){
                //生成token（JWT）
                Map<String,Object>  claims= new HashMap<>();
                claims.put("id",user.getId());
                claims.put("username",user.getUsername());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);  //Result 方法有问题需要修改
            }else{
                return Result.error("用户名不存在或密码错误");
            }
// 查找用户名是否注册存在
//        User user =userService.findByUsername(username);
//        if(user!=null){
//            //进行登录
//            if(userService.login(username, password)){
//                return Result.success("登录成功");
//            }else{
//                return Result.error("密码错误");
//            }
//        }else{
//            return Result.error("用户名不存在");
//        }


    }
    @PostMapping("/userinfo")
    public Result <User> userinfo(/*@RequestHeader("Authorization") String token*/){
//        Map<String,Object>  claims= JwtUtil.parseToken(token);
//        String user = (String) claims.get("username");
        Map<String,Object>  claims= ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);



    }
    @PostMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("更新成功");

//        Map<String,Object>  claims= ThreadLocalUtil.get();
//        String username = (String) claims.get("username");
//        User user1 = userService.findByUsername(username);
//        if(user1!=null){
//            user.setId(user1.getId());
//            user.setUsername(user1.getUsername());
//            userService.update(user);
//            return Result.success("更新成功");
//        }else{
//            return Result.error("用户不存在");
//        }
    }
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam  @URL String avatar){
        //@URL注解：验证字符串是否为合法的URL地址
        userService.updateAvatar(avatar);
        return Result.success("更新头像成功");
    }

    @PostMapping("/update/passPwd")
    public Result updatePassword(@RequestBody Map<String,String> params){
        //校验密码
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        String rePassword = params.get("rePassword");
        if(!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(rePassword)||!StringUtils.hasLength(newPassword)) {
            return Result.error("密码不能为空");
        }
        //校验密码是否正确
         Map<String,Object>  map = ThreadLocalUtil.get();
         String username = (String) map.get("username");
         User user = userService.findByUsername(username);
         if(!user.getPassword().equals(Md5Util.getMD5String(oldPassword))){
            return Result.error("旧密码错误");
         }
         //比较两次被密码是否一致
         if(!newPassword.equals(rePassword)){
            return Result.error("两次密码不一致");
         }
         //检查新密码是否符合要求
         if(!newPassword.matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,16}$")){
            return Result.error("密码必须是6-16位的字母和数字");
         }
         //更新密码
         userService.updatePassword(newPassword);
         return Result.success("更新密码成功");
    }




    @PostMapping("/login/logout")
    public Result success( ) {
        //hello
        return Result.success("登录成功");
    }

    @PostMapping("/login/logouts")
    public String successful( ) {
        //hello
        return "登录成功";
    }



}
